package com.example.user.service.impl;

import com.example.entity.JsonData;
import com.example.user.domain.JwtDto;
import com.example.user.domain.User;
import com.example.user.mapper.JwtMapper;
import com.example.user.mapper.UserMapper;
import com.example.user.service.UserService;
import com.example.user.util.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.Objects;

@Slf4j
@Service
public class UserServiceImpl implements UserService {
    /**
     * 远程数据接口--服务提供者
     */
    private static final String BOOK_URL = "http://localhost:8082";
    //远程服务调用
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private JwtMapper jwtMapper;
    @Override
    public User getUserById(Long id) {
        return userMapper.selectByPrimaryKey(id);
    }

    @Override
    public Object checkLogin(String username, String password) {
        User user = userMapper.selectUserByUsername(username);
        if(username==null|| Objects.isNull(user)){
            return JsonData.buildError("账号未注册",400);
        }
        if(!password.equals(user.getPassword())){
            return JsonData.buildError("账号或密码错误",400);
        }
        List forObject = restTemplate.getForObject(BOOK_URL + "/book/" + user.getId(), List.class);
        user.setBookDtoList(forObject);
        String jwt = JwtUtil.createJWT("login:" + user.getId());
        JwtDto jwtDto = jwtMapper.selectByPrimaryKey("login:" + user.getId());
        if(jwtDto==null){
            jwtMapper.insert(new JwtDto("login:" + user.getId(),jwt));
        }else{
            jwtMapper.updateByPrimaryKey(new JwtDto("login:" + user.getId(),jwt));
        }
        user.setJwtContent(jwt);
        return JsonData.buildSuccess(user);
    }
}
